<template>
	<view class="points-mall-container">
		<!-- 积分信息卡片 -->
		<view class="points-card">
			<view class="points-info">
				<text class="points-label">我的积分</text>
				<text class="points-number">{{ userScore }}</text>
				<text class="points-unit">分</text>
			</view>
			<view class="points-actions">
				<button class="action-btn earn-btn" @click="goToEarnPoints">
					<image class="btn-icon" src="/static/image/points-mall/icons/earn-points.png" mode="aspectFit" />
					<text>赚积分</text>
				</button>
				<button class="action-btn history-btn" @click="goToHistory">兑换记录</button>
			</view>
		</view>

		<!-- 分类标签 -->
		<view class="category-tabs">
			<view 
				v-for="(tab, index) in categoryTabs" 
				:key="index"
				class="tab-item"
				:class="{ active: activeTab === index }"
				@click="switchTab(index)"
			>
				<image v-if="tab.icon" class="tab-icon" :src="tab.icon" mode="aspectFit" />
				<text class="tab-text">{{ tab.name }}</text>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<view 
				v-for="(item, index) in filteredGoods" 
				:key="index"
				class="goods-item"
				@click="goToGoodsDetail(item)"
			>
				<image class="goods-image" :src="item.image" mode="aspectFill" />
				<view class="goods-info">
					<text class="goods-name">{{ item.name }}</text>
					<text class="goods-desc">{{ item.description }}</text>
					<view class="goods-bottom">
											<view class="points-price">
						<image class="points-icon" src="/static/image/points-mall/icons/points-icon.png" mode="aspectFit" />
						<text class="price-text">{{ item.points }}积分</text>
					</view>
						<button class="exchange-btn" @click.stop="exchangeGoods(item)">
							立即兑换
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-if="filteredGoods.length === 0" class="empty-state">
			<image class="empty-icon" src="/static/image/points-mall/icons/points-icon.png" mode="aspectFit" />
			<text class="empty-text">暂无商品</text>
		</view>
	</view>
</template>

<script>
import { store } from '@/uni_modules/uni-id-pages/common/store.js'

export default {
	data() {
		return {
			userScore: 0,
			activeTab: 0,
			categoryTabs: [
				{ name: '全部', id: 'all', icon: '' },
				{ name: '健康用品', id: 'health', icon: '/static/image/points-mall/icons/health-category.png' },
				{ name: '生活用品', id: 'life', icon: '/static/image/points-mall/icons/life-category.png' },
				{ name: '数码产品', id: 'digital', icon: '/static/image/points-mall/icons/digital-category.png' }
			],
			goodsList: [
				{
					id: 1,
					name: '智能手环',
					description: '24小时心率监测，睡眠质量分析',
					points: 5000,
					image: '/static/image/points-mall/goods/smart-watch.png',
					category: 'digital'
				},
				{
					id: 2,
					name: '维生素C片',
					description: '增强免疫力，补充维生素',
					points: 800,
					image: '/static/image/points-mall/goods/vitamin-c.png',
					category: 'health'
				},
				{
					id: 3,
					name: '保温杯',
					description: '316不锈钢，24小时保温',
					points: 1200,
					image: '/static/image/points-mall/goods/thermos.png',
					category: 'life'
				},
				{
					id: 4,
					name: '按摩器',
					description: '颈椎按摩，缓解疲劳',
					points: 2000,
					image: '/static/image/points-mall/goods/massager.png',
					category: 'health'
				},
				{
					id: 5,
					name: '蓝牙耳机',
					description: '无线连接，音质清晰',
					points: 3000,
					image: '/static/image/points-mall/goods/bluetooth-earphone.png',
					category: 'digital'
				},
				{
					id: 6,
					name: '瑜伽垫',
					description: '防滑材质，厚度适中',
					points: 1500,
					image: '/static/image/points-mall/goods/yoga-mat.png',
					category: 'life'
				}
			]
		}
	},
	computed: {
		userInfo() {
			return store.userInfo
		},
		hasLogin() {
			return store.hasLogin
		},
		filteredGoods() {
			if (this.activeTab === 0) {
				return this.goodsList
			}
			const categoryId = this.categoryTabs[this.activeTab].id
			return this.goodsList.filter(item => item.category === categoryId)
		}
	},
	onLoad() {
		this.getUserScore()
	},
	onShow() {
		this.getUserScore()
	},
	methods: {
		// 获取用户积分
		async getUserScore() {
			if (!this.hasLogin) {
				this.userScore = 0
				return
			}
			
			try {
				const db = uniCloud.database()
				// 1) 优先从用户表读取积分
				const res = await db.collection('uni-id-users')
					.where('\"_id\" == $cloudEnv_uid')
					.field('score')
					.limit(1)
					.get()
				let score = res.result && res.result.data && res.result.data[0] ? res.result.data[0].score : undefined
				// 2) 若用户表未设置积分，则回退到积分流水最新余额
				if (typeof score !== 'number') {
					const resScore = await db.collection('uni-id-scores')
						.where('user_id == $env.uid')
						.field('balance')
						.orderBy('create_date', 'desc')
						.limit(1)
						.get()
					score = resScore.result && resScore.result.data && resScore.result.data[0] ? resScore.result.data[0].balance : 0
				}
				this.userScore = typeof score === 'number' ? score : 0
			} catch (error) {
				console.error('获取积分失败:', error)
				this.userScore = 0
			}
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 切换分类标签
		switchTab(index) {
			this.activeTab = index
		},
		
		// 前往赚积分页面
		goToEarnPoints() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},
		
		// 前往兑换记录页面
		goToHistory() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},
		
		// 前往商品详情
		goToGoodsDetail(item) {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},
		
		// 兑换商品
		exchangeGoods(item) {
			if (!this.hasLogin) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			if (this.userScore < item.points) {
				uni.showToast({
					title: '积分不足',
					icon: 'none'
				})
				return
			}
			
			uni.showModal({
				title: '确认兑换',
				content: `确定要使用${item.points}积分兑换"${item.name}"吗？`,
				success: (res) => {
					if (res.confirm) {
						this.confirmExchange(item)
					}
				}
			})
		},
		
		// 确认兑换
		async confirmExchange(item) {
			try {
				uni.showLoading({
					title: '兑换中...'
				})
				
				// 这里应该调用云函数进行积分扣除和商品兑换
				// 暂时模拟成功
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '兑换成功',
						icon: 'success'
					})
					// 刷新积分
					this.getUserScore()
				}, 1500)
				
			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: '兑换失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.points-mall-container {
	background: #f5f8fc;
	min-height: 100vh;
	padding-bottom: 20rpx;
}

.nav-header {
	background: #fff;
	padding: 20rpx 32rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-bottom: 1rpx solid #f0f0f0;
}

.nav-left {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #222;
}

.nav-right {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-icon {
	width: 48rpx;
	height: 48rpx;
}

.points-card {
	background: linear-gradient(135deg, #007AFF, #0056CC);
	margin: 20rpx 32rpx;
	border-radius: 20rpx;
	padding: 40rpx 32rpx;
	color: #fff;
}

.points-info {
	text-align: center;
	margin-bottom: 32rpx;
}

.points-label {
	font-size: 28rpx;
	opacity: 0.9;
	display: block;
	margin-bottom: 16rpx;
}

.points-number {
	font-size: 72rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 8rpx;
}

.points-unit {
	font-size: 24rpx;
	opacity: 0.8;
}

.points-actions {
	display: flex;
	gap: 20rpx;
}

.action-btn {
	flex: 1;
	height: 64rpx;
	border-radius: 32rpx;
	border: none;
	font-size: 28rpx;
	font-weight: 500;
}

.earn-btn {
	background: rgba(255, 255, 255, 0.2);
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8rpx;
}

.btn-icon {
	width: 24rpx;
	height: 24rpx;
}

.history-btn {
	background: rgba(255, 255, 255, 0.1);
	color: #fff;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.category-tabs {
	background: #fff;
	margin: 0 32rpx 20rpx 32rpx;
	border-radius: 16rpx;
	padding: 20rpx 32rpx;
	display: flex;
	gap: 20rpx;
}

.tab-item {
	padding: 16rpx 24rpx;
	border-radius: 24rpx;
	background: #f5f5f5;
	transition: all 0.3s;
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.tab-icon {
	width: 24rpx;
	height: 24rpx;
}

.tab-item.active {
	background: #007AFF;
}

.tab-text {
	font-size: 26rpx;
	color: #666;
}

.tab-item.active .tab-text {
	color: #fff;
}

.goods-list {
	padding: 0 32rpx;
}

.goods-item {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	display: flex;
	gap: 24rpx;
}

.goods-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	flex-shrink: 0;
	background: #f8f9fa;
	object-fit: cover;
}

.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.goods-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #222;
	margin-bottom: 8rpx;
}

.goods-desc {
	font-size: 24rpx;
	color: #666;
	line-height: 1.4;
	margin-bottom: 16rpx;
}

.goods-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.points-price {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.points-icon {
	width: 24rpx;
	height: 24rpx;
}

.price-text {
	font-size: 28rpx;
	font-weight: bold;
	color: #FF6B35;
}

.exchange-btn {
	background: #007AFF;
	color: #fff;
	border: none;
	border-radius: 20rpx;
	padding: 12rpx 24rpx;
	font-size: 24rpx;
}

.empty-state {
	text-align: center;
	padding: 100rpx 32rpx;
}

.empty-icon {
	width: 120rpx;
	height: 120rpx;
	opacity: 0.5;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}
</style>
